/**
 * TypeScript strictness options for ArenaNext
 * Provides UI for configuring TypeScript compiler options
 */

import { showNotification } from "./utils";
import { errorsToIgnore } from "./editorActions";

// 本地存储配置的键名
const STORAGE_KEY = "arenanext_typescript_options";

/**
 * 将编译器配置保存到本地存储
 * @param {Object} compilerOptions - 编译器配置对象
 */
function saveConfigToLocalStorage(compilerOptions) {
  try {
    // 只保存需要持久化的选项
    const optionsToSave = {
      strict: compilerOptions.strict,
      checkJs: compilerOptions.checkJs,
      noImplicitAny: compilerOptions.noImplicitAny,
      strictNullChecks: compilerOptions.strictNullChecks,
      noImplicitThis: compilerOptions.noImplicitThis,
      noUnusedLocals: compilerOptions.noUnusedLocals,
      strictFunctionTypes: compilerOptions.strictFunctionTypes,
      noUnusedParameters: compilerOptions.noUnusedParameters,
      noImplicitReturns: compilerOptions.noImplicitReturns,
      noFallthroughCasesInSwitch: compilerOptions.noFallthroughCasesInSwitch,
      strictPropertyInitialization:
        compilerOptions.strictPropertyInitialization,
    };

    localStorage.setItem(STORAGE_KEY, JSON.stringify(optionsToSave));
  } catch (error) {
    console.error("保存TypeScript配置到本地存储失败:", error);
  }
}

/**
 * 从本地存储读取编译器配置
 * @returns {Object|null} 本地存储的编译器配置，如果不存在则返回null
 */
function loadConfigFromLocalStorage() {
  try {
    const savedConfig = localStorage.getItem(STORAGE_KEY);
    if (savedConfig) {
      return JSON.parse(savedConfig);
    }
    return null;
  } catch (error) {
    console.error("从本地存储读取TypeScript配置失败:", error);
    return null;
  }
}

/**
 * Sets up TypeScript strictness options selector in the scroll wrapper
 * @param {Object} monacoController - The Monaco controller instance
 */
export function setupTypeScriptStrictnessOptions(monacoController) {
  try {
    const monaco = monacoController.monacoController.monaco;

    // 初始化TypeScript编译器选项
    const compilerOptions =
      monaco.languages.typescript.javascriptDefaults.getCompilerOptions() || {};

    // 尝试从本地存储读取配置
    const savedConfig = loadConfigFromLocalStorage();
    if (savedConfig) {
      Object.assign(compilerOptions, savedConfig);
    } else {
      // 如果没有保存的配置，设置默认值（只开启基础选项，关闭严格选项）
      compilerOptions.strict = false;

      // 基础选项
      compilerOptions.allowJs = true;
      compilerOptions.checkJs = true;

      // 类型检查选项
      compilerOptions.noImplicitAny = false;
      compilerOptions.strictNullChecks = false;
      compilerOptions.noImplicitThis = false;

      // 代码质量选项
      compilerOptions.noUnusedLocals = false;
      compilerOptions.noUnusedParameters = false;
      compilerOptions.noImplicitReturns = false;
      compilerOptions.noFallthroughCasesInSwitch = false;
      compilerOptions.strictPropertyInitialization = false;
    }

    // 立即应用所有选项
    monaco.languages.typescript.javascriptDefaults.setCompilerOptions(
      compilerOptions
    );

    // Try to find the scroll wrapper container
    const findScrollWrapper = () => {
      // Try with specific class name first
      let scrollWrapper = document.querySelector(
        ".script-manager_scrollWrapper__iywTk.scroll_boxScrollbar__FIE_E"
      );

      // If not found, try more generic selectors
      if (!scrollWrapper) {
        // Try by class name containing the key parts
        scrollWrapper = document.querySelector(
          "[class*='script-manager_scrollWrapper'][class*='scroll_boxScrollbar']"
        );
      }

      // If still not found, try other potential containers
      if (!scrollWrapper) {
        scrollWrapper = document.querySelector(
          ".script-editor_sidebar__JEGcd, .script-editor_scriptManagerContainer__NGkvr, .script-manager_container__bXxj1"
        );
      }

      // Last resort: find any div that might serve as a container
      if (!scrollWrapper) {
        const possibleContainers = document.querySelectorAll(
          "div[class*='script-manager_']"
        );
        if (possibleContainers.length > 0) {
          // Find a suitable container that's likely to be the scroll wrapper
          scrollWrapper = Array.from(possibleContainers).find(
            (el) =>
              el.clientHeight > 100 &&
              (el.scrollHeight > el.clientHeight ||
                el.querySelector('div[class*="scroll_"]'))
          );
        }
      }

      if (scrollWrapper) {
        console.log("Found scroll wrapper:", scrollWrapper);
        createTypeScriptStrictnessOptions(scrollWrapper, monaco);
      } else {
        // If not found, try again in a short while
        console.log("Scroll wrapper not found, trying again in 1 second");
        setTimeout(findScrollWrapper, 1000);
      }
    };

    findScrollWrapper();
  } catch (error) {
    console.error("设置TypeScript严格度选项失败:", error);
  }
}

/**
 * Creates TypeScript strictness options selector UI
 * @param {HTMLElement} parentElement - The parent element to append to
 * @param {Object} monaco - The Monaco instance
 * @private
 */
function createTypeScriptStrictnessOptions(parentElement, monaco) {
  // Create container
  const container = document.createElement("div");
  container.className = "ts-strictness-options-container";
  container.style.cssText = `
    margin-top: 20px;
    border-top: 1px solid rgba(255, 255, 255, 0.12);
    padding: 18px 12px 0 12px;
  `;

  // Create heading
  const heading = document.createElement("div");
  heading.className = "ts-strictness-heading";
  heading.textContent = "检查严格度(BETA)";
  heading.style.cssText = `
    font-size: 15px;
    font-weight: 600;
    color: #f0f0f0;
    margin-bottom: 14px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: space-between;
    user-select: none;
    padding: 0 4px;
    transition: all 0.2s ease;
  `;

  // Add hover effect to heading
  heading.addEventListener("mouseover", () => {
    heading.style.color = "#ff8100";
  });

  heading.addEventListener("mouseout", () => {
    heading.style.color = "#f0f0f0";
  });

  // Add toggle icon
  const toggleIcon = document.createElement("span");
  toggleIcon.innerHTML = "▼";
  toggleIcon.style.cssText = `
    font-size: 12px;
    transition: transform 0.3s;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 18px;
    height: 18px;
    border-radius: 50%;
  `;
  heading.appendChild(toggleIcon);

  // Create options container
  const optionsContainer = document.createElement("div");
  optionsContainer.className = "ts-strictness-options";
  optionsContainer.style.cssText = `
    display: none;
    flex-direction: column;
  `;

  // Get current compiler options
  const currentOptions =
    monaco.languages.typescript.javascriptDefaults.getCompilerOptions() || {};

  // 创建严格模式一键开关（放在顶部）
  const strictOption = {
    id: "strict",
    label: "严格模式",
    description: "启用所有检查选项",
  };

  // 确保默认情况下所有严格度选项都是开启的
  currentOptions.strict = false;

  const strictSwitchContainer = document.createElement("div");
  strictSwitchContainer.className = "ts-strict-switch-container";
  strictSwitchContainer.style.cssText = `
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 18px;
    padding: 14px;
    background-color: rgba(60, 60, 60, 0.45);
    border-radius: 10px;
    border: 1px solid rgba(255, 129, 0, 0.2);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
    transition: all 0.2s ease;
  `;

  // Add hover effect to the strict switch container
  strictSwitchContainer.addEventListener("mouseover", () => {
    strictSwitchContainer.style.backgroundColor = "rgba(70, 70, 70, 0.5)";
    strictSwitchContainer.style.borderColor = "rgba(255, 129, 0, 0.3)";
  });

  strictSwitchContainer.addEventListener("mouseout", () => {
    strictSwitchContainer.style.backgroundColor = "rgba(60, 60, 60, 0.45)";
    strictSwitchContainer.style.borderColor = "rgba(255, 129, 0, 0.2)";
  });

  const strictSwitchLabel = document.createElement("div");
  strictSwitchLabel.className = "ts-strict-switch-label";
  strictSwitchLabel.style.cssText = `
    display: flex;
    flex-direction: column;
  `;

  const strictSwitchTitle = document.createElement("div");
  strictSwitchTitle.textContent = strictOption.label;
  strictSwitchTitle.style.cssText = `
    font-size: 15px;
    font-weight: 600;
    color: #f5f5f5;
    display: flex;
    align-items: center;
  `;

  // Add an icon to the strict mode title
  const strictIcon = document.createElement("span");
  strictIcon.innerHTML = `
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" style="margin-right: 6px;">
      <path d="M12 2L4 5v6.09c0 5.05 3.41 9.76 8 10.91 4.59-1.15 8-5.86 8-10.91V5l-8-3zm3.2 12.37l-4.5 4.5-2.4-2.4 1.4-1.4 1 1 3.1-3.1 1.4 1.4z" fill="#ff8100"/>
    </svg>
  `;
  strictSwitchTitle.prepend(strictIcon);

  const strictSwitchDesc = document.createElement("div");
  strictSwitchDesc.textContent = strictOption.description;
  strictSwitchDesc.style.cssText = `
    font-size: 13px;
    color: #bbbbbb;
    margin-top: 6px;
  `;

  strictSwitchLabel.appendChild(strictSwitchTitle);
  strictSwitchLabel.appendChild(strictSwitchDesc);

  // 创建开关
  const switchContainer = document.createElement("label");
  switchContainer.className = "ts-strict-switch";
  switchContainer.style.cssText = `
    position: relative;
    display: inline-block;
    width: 52px;
    height: 26px;
  `;

  const switchInput = document.createElement("input");
  switchInput.type = "checkbox";
  switchInput.id = `ts-option-${strictOption.id}`;
  switchInput.checked = false; // Always unchecked by default
  switchInput.style.cssText = `
    opacity: 0;
    width: 0;
    height: 0;
  `;

  const switchSlider = document.createElement("span");
  switchSlider.className = "ts-strict-slider";
  switchSlider.style.cssText = `
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(80, 80, 80, 0.6); 
    transition: .3s;
    border-radius: 26px;
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.3);
  `;

  // 添加开关的滑块
  const switchKnob = document.createElement("span");
  switchKnob.style.cssText = `
    position: absolute;
    content: "";
    height: 20px;
    width: 20px;
    left: 3px;
    bottom: 3px;
    background-color: white;
    transition: .3s;
    border-radius: 50%;
    transform: translateX(0);
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
  `;

  switchSlider.appendChild(switchKnob);
  switchContainer.appendChild(switchInput);
  switchContainer.appendChild(switchSlider);

  // 添加开关的事件处理
  switchInput.addEventListener("change", () => {
    const isChecked = switchInput.checked;

    // Enhanced visual feedback for toggle
    if (isChecked) {
      switchSlider.style.backgroundColor = "#ff8100";
      switchSlider.style.boxShadow = "inset 0 0 5px rgba(255, 129, 0, 0.4)";
      switchKnob.style.transform = "translateX(26px)";
      switchKnob.style.backgroundColor = "#ffffff";
      // Add subtle glow effect when enabled
      switchKnob.style.boxShadow =
        "0 0 8px rgba(255, 129, 0, 0.6), 0 1px 3px rgba(0, 0, 0, 0.3)";
    } else {
      switchSlider.style.backgroundColor = "rgba(80, 80, 80, 0.6)";
      switchSlider.style.boxShadow = "inset 0 0 5px rgba(0, 0, 0, 0.3)";
      switchKnob.style.transform = "translateX(0)";
      switchKnob.style.backgroundColor = "#ffffff";
      switchKnob.style.boxShadow = "0 1px 3px rgba(0, 0, 0, 0.3)";
    }

    // 获取当前选项
    const compilerOptions =
      monaco.languages.typescript.javascriptDefaults.getCompilerOptions();
    compilerOptions[strictOption.id] = isChecked;

    // 更新所有严格选项复选框状态
    strictnessOptions.forEach((opt) => {
      const cb = document.getElementById(`ts-option-${opt.id}`);
      if (cb) {
        cb.checked = isChecked;
        // 更新自定义复选框视觉状态
        const customCheckbox = cb.nextElementSibling;
        if (customCheckbox) {
          if (isChecked) {
            customCheckbox.style.backgroundColor = "#ff8100";
            customCheckbox.style.borderColor = "#ff8100";
            customCheckbox.style.boxShadow = "0 0 4px rgba(255, 129, 0, 0.4)";
          } else {
            customCheckbox.style.backgroundColor = "transparent";
            customCheckbox.style.borderColor = "rgba(120, 140, 180, 0.8)";
            customCheckbox.style.boxShadow = "none";
          }

          customCheckbox.innerHTML = isChecked
            ? `
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z" fill="white"/>
            </svg>
          `
            : "";
        }
      }
      compilerOptions[opt.id] = isChecked;
    });

    // Apply animation to option items when toggling
    const optionItems = document.querySelectorAll(".ts-option-item");
    optionItems.forEach((item, index) => {
      item.style.transition = "transform 0.2s ease, opacity 0.2s ease";
      item.style.transitionDelay = `${index * 0.03}s`;

      if (isChecked) {
        item.style.transform = "translateX(0)";
        item.style.opacity = "1";
      } else {
        item.style.transform = "translateX(0)";
        item.style.opacity = "0.8";
      }
    });

    // 应用更新的编译器选项
    monaco.languages.typescript.javascriptDefaults.setCompilerOptions(
      compilerOptions
    );

    // 保存配置到本地存储
    saveConfigToLocalStorage(compilerOptions);

    // 如果关闭所有选项，完全禁用诊断
    if (!isChecked) {
      monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
        noSemanticValidation: true, // 禁用语义验证
        noSyntaxValidation: true, // 禁用语法验证
        diagnosticCodesToIgnore: [1, 2, 3, 4, 5], // 忽略所有诊断代码
      });
      showNotification(`已禁用所有脚本检查`);
    } else {
      // 重新启用诊断但保留用户忽略的错误
      const errorsToIgnore = [80001]; // 原始要忽略的错误
      monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
        noSemanticValidation: false,
        noSyntaxValidation: false,
        diagnosticCodesToIgnore: errorsToIgnore,
      });
      showNotification(`TypeScript严格模式已启用`);
    }
  });

  strictSwitchContainer.appendChild(strictSwitchLabel);
  strictSwitchContainer.appendChild(switchContainer);

  // 创建各个严格选项
  const strictnessOptions = [
    // ========== 基础语法检查 ==========

    {
      id: "checkJs",
      label: "允许检查脚本",
      description: "在.js文件中报告类型错误",
      category: "基础",
    },

    // ========== 类型严格性 ==========
    {
      id: "noImplicitAny",
      label: "禁止隐式any",
      description: "禁止未明确类型的变量隐式推断为any",
      category: "类型",
    },
    {
      id: "strictNullChecks",
      label: "严格空值检查",
      description: "明确处理null/undefined可能性",
      category: "类型",
    },
    {
      id: "noImplicitThis",
      label: "禁止隐式this",
      description: "禁止未类型化的this上下文",
      category: "类型",
    },

    // ========== 代码质量 ==========
    {
      id: "noUnusedLocals",
      label: "未使用局部变量",
      description: "检查未使用的局部变量",
      category: "质量",
    },
    {
      id: "strictFunctionTypes",
      label: "严格函数类型",
      description: "对函数参数进行更严格的逆变检查",
      category: "质量",
    },
    {
      id: "noUnusedParameters",
      label: "未使用参数",
      description: "检查未使用的函数参数",
      category: "质量",
    },
    {
      id: "noImplicitReturns",
      label: "隐式返回检查",
      description: "确保函数所有路径都有返回值",
      category: "质量",
    },
    {
      id: "noFallthroughCasesInSwitch",
      label: "Switch穿透检查",
      description: "禁止switch case语句穿透执行",
      category: "质量",
    },
    {
      id: "strictPropertyInitialization",
      label: "严格属性初始化",
      description: "确保所有属性都被初始化",
      category: "质量",
    },
  ];

  // 应用更新后的编译器选项
  monaco.languages.typescript.javascriptDefaults.setCompilerOptions(
    currentOptions
  );

  // Group options by category for better organization
  const groupedOptions = {};
  strictnessOptions.forEach((option) => {
    if (!groupedOptions[option.category]) {
      groupedOptions[option.category] = [];
    }
    groupedOptions[option.category].push(option);
  });

  // Create checkboxes for each option, organized by category
  Object.keys(groupedOptions).forEach((category) => {
    // Create category heading
    const categoryHeading = document.createElement("div");
    categoryHeading.className = "ts-option-category";
    categoryHeading.textContent =
      category === "基础"
        ? "基础选项"
        : category === "类型"
        ? "类型检查"
        : category === "质量"
        ? "代码质量"
        : category;
    categoryHeading.style.cssText = `
      font-size: 13px;
      font-weight: 600;
      color: #bbbbbb;
      margin: 8px 0 10px 2px;
      padding-bottom: 6px;
      border-bottom: 1px solid rgba(255, 255, 255, 0.08);
    `;
    optionsContainer.appendChild(categoryHeading);

    // Create options for this category
    groupedOptions[category].forEach((option) => {
      const optionDiv = document.createElement("div");
      optionDiv.className = "ts-option-item";
      optionDiv.style.cssText = `
        display: flex;
        align-items: center;
        margin-bottom: 10px;
        padding: 8px 10px;
        border-radius: 6px;
        transition: all 0.2s ease;
        border: 1px solid transparent;
      `;

      // Add hover effect
      optionDiv.addEventListener("mouseover", () => {
        optionDiv.style.backgroundColor = "rgba(60, 60, 60, 0.5)";
        optionDiv.style.borderColor = "rgba(255, 129, 0, 0.15)";
        optionDiv.style.transform = "translateX(2px)";
      });

      optionDiv.addEventListener("mouseout", () => {
        optionDiv.style.backgroundColor = "rgba(50, 50, 50, 0.3)";
        optionDiv.style.borderColor = "transparent";
        optionDiv.style.transform = "translateX(0)";
      });

      // Modern checkbox container
      const checkboxContainer = document.createElement("div");
      checkboxContainer.style.cssText = `
        position: relative;
        margin-right: 12px;
        width: 18px;
        height: 18px;
      `;

      // Hidden actual checkbox
      const checkbox = document.createElement("input");
      checkbox.type = "checkbox";
      checkbox.id = `ts-option-${option.id}`;
      checkbox.className = "ts-option-checkbox";
      checkbox.checked = option.id === "checkJs" ? true : false;
      checkbox.style.cssText = `
        position: absolute;
        opacity: 0;
        width: 100%;
        height: 100%;
        z-index: 2;
        cursor: pointer;
      `;

      // Custom checkbox visual
      const customCheckbox = document.createElement("div");
      customCheckbox.style.cssText = `
        position: absolute;
        top: 0;
        left: 0;
        width: 18px;
        height: 18px;
        border-radius: 4px;
        border: 1.5px solid rgba(120, 140, 180, 0.8);
        background-color: ${
          option.id === "checkJs" ? "#ff8100" : "transparent"
        };
        transition: all 0.2s ease;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: ${
          option.id === "checkJs" ? "0 0 4px rgba(255, 129, 0, 0.4)" : "none"
        };
      `;

      customCheckbox.innerHTML =
        option.id === "checkJs"
          ? `
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z" fill="white"/>
          </svg>
        `
          : ``;

      // Add change event listener to checkbox
      checkbox.addEventListener("change", function () {
        // Update visual state with animation
        if (this.checked) {
          customCheckbox.style.backgroundColor = "#ff8100";
          customCheckbox.style.borderColor = "#ff8100";
          customCheckbox.style.boxShadow = "0 0 4px rgba(255, 129, 0, 0.4)";
          customCheckbox.style.transform = "scale(1.05)";
          setTimeout(() => {
            customCheckbox.style.transform = "scale(1)";
          }, 150);
        } else {
          customCheckbox.style.backgroundColor = "transparent";
          customCheckbox.style.borderColor = "rgba(120, 140, 180, 0.8)";
          customCheckbox.style.boxShadow = "none";
        }

        customCheckbox.innerHTML = this.checked
          ? `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z" fill="white"/>
            </svg>`
          : "";

        // Get current compiler options
        const compilerOptions =
          monaco.languages.typescript.javascriptDefaults.getCompilerOptions();

        // Update compiler option
        compilerOptions[option.id] = this.checked;

        // Update main switch state
        const mainSwitch = document.getElementById("ts-option-strict");
        if (mainSwitch) {
          if (!this.checked) {
            // If any option is unchecked, turn off main switch
            mainSwitch.checked = false;
            const switchSlider = mainSwitch.nextElementSibling;
            if (switchSlider) {
              switchSlider.style.backgroundColor = "rgba(80, 80, 80, 0.6)";
              switchSlider.style.boxShadow = "inset 0 0 5px rgba(0, 0, 0, 0.3)";
              const switchKnob = switchSlider.querySelector("span");
              if (switchKnob) {
                switchKnob.style.transform = "translateX(0)";
                switchKnob.style.boxShadow = "0 1px 3px rgba(0, 0, 0, 0.3)";
              }
            }
            compilerOptions.strict = false;
          } else if (
            strictnessOptions.every((opt) => {
              const cb = document.getElementById(`ts-option-${opt.id}`);
              return cb && cb.checked;
            })
          ) {
            // If all options are checked, turn on main switch
            mainSwitch.checked = true;
            const switchSlider = mainSwitch.nextElementSibling;
            if (switchSlider) {
              switchSlider.style.backgroundColor = "#ff8100";
              switchSlider.style.boxShadow =
                "inset 0 0 5px rgba(255, 129, 0, 0.4)";
              const switchKnob = switchSlider.querySelector("span");
              if (switchKnob) {
                switchKnob.style.transform = "translateX(26px)";
                switchKnob.style.boxShadow =
                  "0 0 8px rgba(255, 129, 0, 0.6), 0 1px 3px rgba(0, 0, 0, 0.3)";
              }
            }
            compilerOptions.strict = true;
          }
        }

        // Force disable diagnostics when all options are unchecked
        if (
          strictnessOptions.every((opt) => {
            const cb = document.getElementById(`ts-option-${opt.id}`);
            return cb && !cb.checked;
          })
        ) {
          // If ALL options are disabled, completely disable diagnostics
          monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
            noSemanticValidation: true, // Disable semantic validation
            noSyntaxValidation: true, // Disable syntax validation
            diagnosticCodesToIgnore: [1, 2, 3, 4, 5], // Ignore all diagnostic codes
          });
          showNotification(`已禁用所有脚本检查，重新启用任意选项将恢复检查`);
        } else {
          // Re-enable diagnostics but keep user-ignored errors
          monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
            noSemanticValidation: false,
            noSyntaxValidation: false,
            diagnosticCodesToIgnore: errorsToIgnore,
          });
        }

        // Apply updated compiler options
        monaco.languages.typescript.javascriptDefaults.setCompilerOptions(
          compilerOptions
        );

        // 保存配置到本地存储
        saveConfigToLocalStorage(compilerOptions);

        // Show notification
        if (!this.checked) {
          showNotification(`脚本检查选项 ${option.id} 已禁用`);
        } else {
          showNotification(`脚本检查选项 ${option.id} 已启用`);
        }
      });

      checkboxContainer.appendChild(checkbox);
      checkboxContainer.appendChild(customCheckbox);

      // Create a container for the label and description
      const labelContainer = document.createElement("div");
      labelContainer.style.cssText = `
        display: flex;
        flex-direction: column;
        flex: 1;
      `;

      const labelEl = document.createElement("label");
      labelEl.htmlFor = checkbox.id;
      labelEl.textContent = option.label;
      labelEl.style.cssText = `
        font-size: 14px;
        color: #f0f0f0;
        cursor: pointer;
        user-select: none;
        font-weight: 500;
      `;

      // Add description text below label
      const descriptionEl = document.createElement("div");
      descriptionEl.textContent = option.description;
      descriptionEl.style.cssText = `
        font-size: 12px;
        color: #aaaaaa;
        margin-top: 3px;
      `;

      labelContainer.appendChild(labelEl);
      labelContainer.appendChild(descriptionEl);

      optionDiv.appendChild(checkboxContainer);
      optionDiv.appendChild(labelContainer);
      optionsContainer.appendChild(optionDiv);
    });
  });

  // Add toggle functionality with animation
  heading.addEventListener("click", () => {
    const isVisible = optionsContainer.style.display === "flex";

    if (isVisible) {
      // Add closing animation
      optionsContainer.style.opacity = "0";
      optionsContainer.style.transform = "translateY(-10px)";

      // Wait for animation to complete before hiding
      setTimeout(() => {
        optionsContainer.style.display = "none";
      }, 200);

      toggleIcon.style.transform = "rotate(0deg)";
    } else {
      // Show immediately but animate in
      optionsContainer.style.display = "flex";
      optionsContainer.style.opacity = "0";
      optionsContainer.style.transform = "translateY(-10px)";

      // Trigger animation after a small delay
      setTimeout(() => {
        optionsContainer.style.opacity = "1";
        optionsContainer.style.transform = "translateY(0)";
      }, 10);

      toggleIcon.style.transform = "rotate(180deg)";
    }
  });

  // Assemble the component
  container.appendChild(heading);
  optionsContainer.appendChild(strictSwitchContainer);

  container.appendChild(optionsContainer);

  // Add to parent
  parentElement.appendChild(container);

  // Add CSS animation definition for the container
  const styleEl = document.createElement("style");
  styleEl.textContent = `
    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(-5px); }
      to { opacity: 1; transform: translateY(0); }
    }
    
    .ts-option-item:hover .ts-option-checkbox + div {
      border-color: #ff8100 !important;
    }
  `;
  document.head.appendChild(styleEl);

  // 检查本地配置并更新UI状态
  setTimeout(() => {
    const savedConfig = loadConfigFromLocalStorage();
    if (savedConfig) {
      // 更新严格模式开关
      const strictSwitch = document.getElementById("ts-option-strict");
      if (strictSwitch && typeof savedConfig.strict !== "undefined") {
        strictSwitch.checked = savedConfig.strict;
        const switchSlider = strictSwitch.nextElementSibling;
        if (switchSlider) {
          switchSlider.style.backgroundColor = savedConfig.strict
            ? "#ff8100"
            : "rgba(80, 80, 80, 0.6)";
          switchSlider.style.boxShadow = savedConfig.strict
            ? "inset 0 0 5px rgba(255, 129, 0, 0.4)"
            : "inset 0 0 5px rgba(0, 0, 0, 0.3)";

          const switchKnob = switchSlider.querySelector("span");
          if (switchKnob) {
            switchKnob.style.transform = savedConfig.strict
              ? "translateX(26px)"
              : "translateX(0)";
            switchKnob.style.boxShadow = savedConfig.strict
              ? "0 0 8px rgba(255, 129, 0, 0.6), 0 1px 3px rgba(0, 0, 0, 0.3)"
              : "0 1px 3px rgba(0, 0, 0, 0.3)";
          }
        }
      }

      // 更新各个选项复选框，添加视觉效果
      strictnessOptions.forEach((option) => {
        if (typeof savedConfig[option.id] !== "undefined") {
          const cb = document.getElementById(`ts-option-${option.id}`);
          if (cb) {
            cb.checked = savedConfig[option.id];
            const customCheckbox = cb.nextElementSibling;
            if (customCheckbox) {
              customCheckbox.style.backgroundColor = savedConfig[option.id]
                ? "#ff8100"
                : "transparent";
              customCheckbox.style.borderColor = savedConfig[option.id]
                ? "#ff8100"
                : "rgba(120, 140, 180, 0.8)";
              customCheckbox.style.boxShadow = savedConfig[option.id]
                ? "0 0 4px rgba(255, 129, 0, 0.4)"
                : "none";

              customCheckbox.innerHTML = savedConfig[option.id]
                ? `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z" fill="white"/>
                  </svg>`
                : "";
            }
          }
        }
      });

      // Automatically open the options panel if any setting is enabled
      if (
        savedConfig.strict ||
        Object.values(savedConfig).some((value) => value === true)
      ) {
        setTimeout(() => {
          heading.click();
        }, 500);
      }
    }
  }, 100);
}
